import groovy.sql.Sql
import org.primefaces.event.FileUploadEvent
import org.primefaces.model.TreeNode
import org.primefaces.model.DefaultTreeNode
import org.primefaces.model.file.UploadedFile;
import org.primefaces.model.StreamedContent
import org.primefaces.model.DefaultStreamedContent
import java.sql.SQLException

public execute(o) {
    return new mc(o)
}

class mc {
    def mypara
    def treeList = ["ID": null, "EmployeeID": null, "Name": null, "Position": null, "ManagerID": null, "Attachment": null];
    TreeNode root;  //定义树形集合
    TreeNode Node = null;
    def shuru1 = true;  //输入框
    def sxan = false;  //刷新按钮
    def xgan = false;  //修改按钮
    def scan = true;  //删除按钮
    def bcan = true;  //保存按钮
    def qxan = true;  //取消按钮
    def bcstatus = "新增"; //保存按钮状态（是新增还是修改）

    // 新增 attachmentImage 属性
    byte[] attachmentImage; // 用于存储附件内容（如图片的字节数组）

    // Getter 和 Setter 方法
    byte[] getAttachmentImage() {
        return attachmentImage
    }

    void setAttachmentImage(byte[] attachmentImage) {
        this.attachmentImage = attachmentImage
    }

    String attachmentPath; // 用于存储附件路径

    // Getter 和 Setter 方法
    String getAttachmentPath() {
        return attachmentPath
    }

    void setAttachmentPath(String attachmentPath) {
        this.attachmentPath = attachmentPath
    }

    public mc(f) {
        this.mypara = f;
        selectTreeTable()
    }

    /*
    * 点击刷新按钮
    */
    def shuaxin() {
        selectTreeTable();
    }

    /*
    * 树形图
    * 查询人员信息
    */
    def selectTreeTable() {
        root = new DefaultTreeNode("Root Node", null);
        def conn = null
        def jiedian
        def gen
        try {
            conn = Sql.newInstance(mypara.hqcon(1))
            jiedian = conn.rows("SELECT ID,EmployeeID, Name, Position, ManagerID, Attachment FROM Employee;")
            if (jiedian != []) {
                gen = sjzl(jiedian)
                root = digui(gen, root) as TreeNode
            }
            clearInputFields()
        } catch (SQLException e) {
            e.printStackTrace()
            println("SQL 错误: ${e.message}")
        } catch (Exception e) {
            e.printStackTrace()
            println("发生错误: ${e.message}")
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    /*
    * 数据整理方法
    */
    def sjzl(def jieguo) {
        def one = [:];
        def two = [];

        for (i in jieguo) {
            one.put(i.EmployeeID.toString(), i)
            i.put("x", [])
        }
        for (i in jieguo) {
            if (i['ManagerID']) {
                def parentId = i.ManagerID.toString()
                def parentNode = one[parentId]
                if (parentNode != null) {
                    parentNode["x"].add(i)
                } else {
                    println "警告: 找不到父节点 ID ${parentId}"
                    two.add(i) // 将其视为顶层节点
                }
            } else {
                two.add(i)
            }
        }
        return two;
    }

    /*
    * 递归算法（进行数据递归）
    */
    def digui(def list, def root1) {
        for (i in list) {
            TreeNode documents = new DefaultTreeNode(i, root1);
            if (i['x']) {
                digui(i['x'], documents)
            }
        }
        return root1;
    }

    /*
    * ajax触发事件
    */
    def ajax() {
        sxan = false;
        treeList = ["ID": null, "EmployeeID": null, "Name": null, "Position": null, "ManagerID": null, "Attachment": null];
        if (Node != null && Node.getData() instanceof Map) {
            def data = Node.getData()
            treeList.each { key, value ->
                treeList[key] = data[key]
            }
            // 如果有有效的节点被选中，则启用删除按钮
            scan = false
        } else {
            println "Node 未定义或数据格式不正确"
            scan = true
        }
    }

    /*
    * 定义Node
    */
    def setNode(TreeNode node) {
        this.Node = node
        ajax()
    }

    /*
    * 新增
    */
    def xinzeng() {
        sxan = true;
        shuru1 = false;
        xgan = true;
        scan = true;
        bcan = false;
        qxan = false;
        bcstatus = "新增";
    }

    /*
    * 取消
    */
    def quxiao() {
        sxan = false;
        xgan = false;
        shuru1 = true;
        scan = true;
        bcan = true;
        qxan = true;
        clearInputFields()
    }

    /*
    * 保存
    */
    def baocun() {
        def conn = null;
        sxan = false;
        xgan = false;
        shuru1 = true;
        scan = true;
        bcan = true;
        qxan = true;
        def chongfu;
        def torf = notnull(treeList);
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(1));
            if (torf) {
                def sqlstr = "select EmployeeID from Employee where EmployeeID='" + treeList.getAt("EmployeeID") + "'";
                chongfu = conn.rows(sqlstr);
                if (bcstatus.equals("新增")) {
                    bcstatus = "新增"
                    if (chongfu == []) {    //判断没有重复编码进行新增
                        def sqlstr2 = "insert into Employee(EmployeeID, Name, Position, ManagerID, Attachment) values(?, ?, ?, ?, ?)"
                        def params = [treeList.getAt("EmployeeID"), treeList.getAt("Name"), treeList.getAt("Position"), treeList.getAt("ManagerID"), treeList.getAt("Attachment")]
                        treeList.ID = conn.executeInsert(sqlstr2, params)[0][0]
                        selectTreeTable();  //进行前台左侧页面更新
                        mypara.msg("新增成功！");
                        quxiao();
                        clearInputFields()
                    } else {
                        mypara.msg("此编码已存在哦，请重新输入新的编码！");
                    }
                }else if (bcstatus.equals("修改")) {
                    def sqlstr3 = "update Employee set Name = :Name, Position = :Position, ManagerID = :ManagerID, Attachment = :Attachment where EmployeeID = :EmployeeID"
                    def params2 = [
                            Name: treeList.getAt("Name"),
                            Position: treeList.getAt("Position"),
                            ManagerID: treeList.getAt("ManagerID"),
                            Attachment: treeList.getAt("Attachment"),
                            EmployeeID: treeList.getAt("EmployeeID")
                    ]

                    conn.executeUpdate(sqlstr3, params2)
                    selectTreeTable();  // 进行前台左侧页面更新
                    mypara.msg("修改成功！");
                    quxiao();
                    clearInputFields()
                }
            }else{
                mypara.msg("有未填写内容，请填写完整！");
            }
        } catch (Exception e) {
            mypara.msg(bcstatus + "失败！");
            println "这是报错： " + e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }

    }

    /*
    * 附件上传
    */
    def handleFileUpload(FileUploadEvent event) {
        try {
            // 定义文件保存的目录
            def saveDirectory = "D:\\01-file"
            // 确保目录存在，如果不存在则创建
            def directory = new File(saveDirectory)
            if (!directory.exists()) {
                directory.mkdirs()

            }
            UploadedFile file = event.getFile();

            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID().toString() + "_" + file.getFileName();
            mypara.msg("文件名"+uniqueFileName)

            // 构建安全的文件路径
            def filePath = saveDirectory+"\\"+uniqueFileName;
            InputStream input = file.getInputStream()
            OutputStream output = new FileOutputStream(new File(filePath))
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }

            // 保存文件路径到 treeList
            treeList["Attachment"] = filePath
            // 提示上传成功
            mypara.msg("文件上传成功！")
        } catch (Exception e) {
            // 提示用户具体的错误信息
            mypara.msg("文件上传失败: ${e.message}")
        }
    }
    /*
    * 判断输入不为空
    */
    def notnull(def treeList) {
        def torf = true;
        if (treeList.getAt("Name").equals("")) {
            torf = false;
        }
        if (treeList.getAt("Position").equals("")) {
            torf = false;
        }
        return torf;
    }

    /*
    * 清空输入框
    */
    def clearInputFields() {
        treeList.each { key, value ->
            treeList[key] = null
        }
        shuru1 = true;
    }

    /*
    * 删除
    */
    def shanchu(){
        def conn=null;
        def torf=true;
        if(!treeList.getAt("EmployeeID").equals("")&&!treeList.getAt("EmployeeID").equals(null)){
            try{
                conn=groovy.sql.Sql.newInstance(mypara.hqcon(1))
                // 检查是否有下级员工
                def sqlCheck = "SELECT COUNT(*) as num FROM Employee WHERE ManagerID = ?"
                def result = conn.firstRow(sqlCheck, [treeList.getAt("EmployeeID")])
                if (result.num == 0) {
                    // 如果没有下级员工，执行删除操作
                    def sqlDelete = "DELETE FROM Employee WHERE EmployeeID = ?"
                    conn.execute(sqlDelete, [treeList.getAt("EmployeeID")])

                    // 删除附件文件
                    def attachmentPath = treeList.getAt("Attachment")
                    if (attachmentPath) {
                        new File(attachmentPath).delete()
                    }

                    mypara.msg("删除成功！")
                    selectTreeTable()  // 更新树形结构
                    clearInputFields()  // 清空输入框
                } else {
                    mypara.msg("此员工有下级员工，不能删除！")
                }
                clearInputFields()
            }catch(Exception e){
                println "删除报错： "+e.printStackTrace();
            }finally{
                if(conn!=null){
                    conn.close();
                }
            }
        }else{
            mypara.msg("请输入要删除的人员信息！");
        }
    }

    /*
    * 修改
    */
    def xiugai(){
        shuru1 = false;  //输入框
        sxan = true;  //刷新按钮
        xgan = true;  //修改按钮
        scan = false;  //删除按钮
        bcan = false;  //保存按钮
        qxan = false;  //取消按钮
        bcstatus = "修改"
    }


    // 动态生成图片流
    StreamedContent getAttachmentImageStream() {
        if (attachmentImage != null) {
            try {
                InputStream input = new ByteArrayInputStream(attachmentImage)
                println "调试: 创建InputStream成功，大小=${attachmentImage.length}字节"

                def stream = DefaultStreamedContent.builder()
                        .stream({ -> input })
                        .contentType("image/jpeg")
                        .build()

                println "调试: 成功创建StreamedContent"
                return stream
            } catch (Exception e) {
                println "创建StreamedContent时出错: ${e.message}"
                e.printStackTrace()
                return null
            }
        }
        return null
    }
    /*
     * 查看附件
     */
    def viewAttachment(node) {
        try {
            def attachmentPath = node["Attachment"]
            println "调试: 附件路径 = ${attachmentPath}"

            if (attachmentPath) {
                def file = new File(attachmentPath)
                println "调试: 文件是否存在 = ${file.exists()}"
                println "DEBUG: 文件绝对路径=${file.absolutePath}, 可读=${file.canRead()}"
                if (file.exists()) {
                    def fileExtension = attachmentPath.substring(attachmentPath.lastIndexOf(".") + 1).toLowerCase()
                    switch (fileExtension) {
                        case ["jpg", "jpeg", "png", "gif"]:
                            this.attachmentImage = file.bytes
                            println "调试: 图片字节大小 = ${attachmentImage?.length}"
                            this.attachmentPath = null
                            return
                        case "pdf":
                            this.attachmentPath = attachmentPath
                            this.attachmentImage = null
                            return
                        default:
                            this.attachmentPath = attachmentPath
                            this.attachmentImage = null
                            return
                    }
                }
            }
            mypara.msg("附件无效或不存在")
        } catch (Exception e) {
            mypara.msg("附件加载失败: ${e.message}")
            e.printStackTrace()
        }
    }
}